# -*- coding: UTF-8 -*-
"""
@Project ：swift-forge-engine 
@File    ：upload_service.py
@IDE     ：PyCharm 
@Author  ：Tony.Gan
@Date    ：2025/3/12 21:48 
@Des     ：
"""

import os


from fastapi import File

from App.common.exception.errors import CustomError
from App.config.path_conf import STATIC_DIR
from App.utils.generate_string import random_str


async def upload_image(files: File(...), _type: str) -> str:
    """
    将文件保存到服务器的指定目录中
    :param _type:
    :param files:
    :return:
    """
    file = await files.read()

    # 用.分割文件名，最后一个元素为文件后缀名，并全部转为小写字母
    suffix = files.filename.split(".")[-1].lower()
    if suffix not in ["bmp", "jpg", "jpeg", "png", "gif"]:
        raise CustomError(message="文件格式不正确，该接口仅支持: bmp, jpg, jpeg, png, gif格式的文件")

    dir_path = STATIC_DIR + f"/{_type}/"
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    file_name = random_str() + "." + suffix
    # 拼接文件路径
    os_path = dir_path + file_name

    # 保存文件
    with open(os_path, "wb") as f:
        f.write(file)
    new_file_path = f"/static/{_type}/{file_name}"
    return new_file_path

